package com.ruanjian.reggie.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanjian.reggie.common.CustomException;
import com.ruanjian.reggie.entity.Category;
import com.ruanjian.reggie.entity.Dish;
import com.ruanjian.reggie.entity.Setmeal;
import com.ruanjian.reggie.mapper.CategoryMapper;
import com.ruanjian.reggie.service.CategoryService;
import com.ruanjian.reggie.service.DishService;
import com.ruanjian.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImp extends ServiceImpl<CategoryMapper, Category> implements CategoryService  {

    //同过autowired注入两个实体
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     *
     * @param id
     * 根据id删除分类，删除之前需要进行判断
     */
    @Override
    public void remove(Long id) {
        //查询之前分类是否关联了菜品，如果已经关联，抛出一个业务异常
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("category_id",id);
        int count = dishService.count(dishQueryWrapper);
        if(count > 0){
            throw new CustomException("当前分类下关联了菜品，不能删除");

        }
        /*这是两种条件构造器他们是等值的
        * */
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if(count1 > 0){
            throw new CustomException("当前菜品下关联了套餐，不能够删除");

        }
        super.removeById(id);

    }
}
